package de.tuberlin.dima.dkey.examples;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import de.tuberlin.dima.dkey.client.Client;
import de.tuberlin.dima.dkey.client.GTree;
import de.tuberlin.dima.dkey.util.JsonTreeHelper;

public class JsonTreeGenerator {


/**
 * This program reads in a json file that defines a tree line by line and then adds it to the server
 * After all that is done it calls commit
 */

	public static void main(String[] args) {

		BasicConfigurator.configure();
		Logger.getRootLogger().setLevel(Level.INFO);

		int counter = 0;
		
		long time = System.currentTimeMillis();
		
		try {
			BufferedReader bufRead = new BufferedReader(new FileReader(args[0]));
            String line = bufRead.readLine();
			Client client = new Client("localhost", 8080);
			
			JsonTreeHelper creator = new JsonTreeHelper();
			
            while (line != null){
            	GTree tree = creator.createTree(line);
         	
            	counter++;

            	//Check if the tree was created (Empty line will trigger null)
            	if (tree != null && tree.isValid() ){
        			//Send it to the server

        			try {
        				
        				client.addTree(tree);

        			} catch (Exception e) {
        				e.printStackTrace();
        				return;
        			}
        			
        		}else{
        			if(tree != null){
						System.err.println("Tree is not valid:\n" + tree.toString() );        				
        			}
        		}
                //System.out.println(line);
                line = bufRead.readLine();
            }
			BlockingQueue<String> answer = client.getReturnQueue();
			while(!answer.isEmpty()){
				System.out.println(answer.poll());
			}
			
			
            
			client.commit();
			
			client.end();
            
            bufRead.close();
			
        }catch (ArrayIndexOutOfBoundsException e){
			System.out.println("Usage: java ReadFile filename\n");			
		}catch (IOException e){
            e.printStackTrace();
        } catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		time = System.currentTimeMillis() - time;
		
		System.out.println("Parsed " + counter + " trees");
		System.out.println("It took " + time + " milliseconds");
		
	}

}
